package com.kara.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.appfuse.dao.hibernate.GenericDaoHibernate;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.kara.dao.SchoolYeadDao;
import com.kara.entity.SchoolYear;

public class SchoolYearDaoImpl extends GenericDaoHibernate<SchoolYear, Long> implements SchoolYeadDao{
	
	@Autowired
	SessionFactory sessionFactory;
	
	
	public SchoolYearDaoImpl() {
		super(SchoolYear.class);
	}
	public SchoolYearDaoImpl(Class<SchoolYear> persistentClass) {
		super(persistentClass);
	}

	public SchoolYear getCurrentSchoolYear() {
		
		List<SchoolYear> allYears = getAll();
		List<SchoolYear> currentYears = new ArrayList<SchoolYear>();
		for (SchoolYear a : allYears) {
			if (a.getIsCurrentSchoolYear()){
				currentYears.add(a);
			}
		}
		if (currentYears.size()> 1){
			throw new IllegalStateException("Found more than one current year, only support for one school year at time");
		}
		return currentYears.get(0);
	}
	public List<SchoolYear> getSchoolYearBetWeenDates(Date from, Date to) {
		
		StringBuilder queryString = new StringBuilder("from SchoolYear where startDate < :from and endDate > :to");
		Query query = sessionFactory.getCurrentSession().createQuery(queryString.toString());
		query.setDate("from", from);
		query.setDate("to", to);
		@SuppressWarnings("unchecked") List<SchoolYear> list = query.list();
		return list;
	}

}